use File::Which;

my $commandArg = $ARGV[0];
my $diffFile = $ARGV[1];

my $p4Exists = which('p4.exe');
my $svnExists = which('svn.exe');

my $inClient = 0;

if ($p4Exists)
{
	my $command = "p4.exe info";
	open(P4, "$command |");
	my $p4Port;
	my $userName;
	while (<P4>)
	{
	  if (/Server address: (.+)/)
	  {
		$p4Port = "-p " . $1;
	  }
	  elsif (/User name: (.+)/)
	  {
		$userName = "-u " . $1;
	  }
	}
	close(P4);

	$command = "p4.exe $p4Port $userName workspaces";
	open(P4W, "$command |");
	my $workspace;
	my $greatestLength = 0;
	while (<P4W>)
	{
	  if (/[^\s]+ ([^\s]+) [^\s]+ root ([^']+)'/)
	  {
		my $currentClient = $1;
		my $checkingDirectory = $2;
		chop($checkingDirectory);
		$checkingDirectory =~ s/\//\\/g;
		my $currentLength = length($checkingDirectory);
		if ($currentLength < $greatestLength)
		{
		  next;
		}
		if (index($diffFile, $checkingDirectory) == -1)
		{
		  next;
		}
		$greatestLength = $currentLength;
		$workspace = "-c " . $currentClient;
	  }
	}
	close(P4W);

	$command = "p4.exe $p4Port $userName $workspace fstat $diffFile";
	open(P4, "$command |");
	while (<P4>)
	{
	  if (/depotFile/)
	  {
		$inClient = 1;
	  }
	}
	close(P4);
}

my $command;
if ($inClient)
{
  if ($commandArg eq "edit" || $commandArg eq "add")
  {
	$command = "p4.exe $p4Port $userName $workspace $commandArg $diffFile"
  }
  else
  {
    $command = "p4v.exe $p4Port $userName $workspace -cmd \"$commandArg $diffFile\"";
  }
}
elsif($svnExists)
{
  if ($commandArg eq "add")
  {
    $command = "TortoiseProc.exe /command:add /path:$diffFile";
  }
  elsif ($commandArg eq "prevdiff")
  {
    $command = "TortoiseProc.exe /command:diff /path:$diffFile";
  }
  elsif ($commandArg eq "annotate")
  {
    $command = "TortoiseProc.exe /command:blame /startrev:1 /endrev:-1 /path:$diffFile";
  }
  elsif ($commandArg eq "tree")
  {
    $command = "TortoiseProc.exe /command:revisiongraph /path:$diffFile";
  }
  elsif ($commandArg eq "history")
  {
    $command = "TortoiseProc.exe /command:log /path:$diffFile";
  }
}

if ($command)
{
	system $command;
}

